package com.humngyang.com.hmy.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class DateUtil {

    private static Logger logger = LoggerFactory.getLogger(DateUtil.class);

    public final static String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";

    public final static String FORMAT_DATE = "yyyy-MM-dd";

    public final static String FORMAT_SEQNUM = "yyyyMMddHHmmss";


    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 根据小时获取到毫秒数
     *
     * @return
     */
    public static Long getLong(Integer hour) {
        long l = 1000 * hour * 60 * 60;// 一天的毫秒数
        return l;
    }

    public static Date nowDateTime() {
        return dateTime(new Date());
    }

    public static String nowDateTimeStr() {
        return format(new Date());
    }

    public static Date dateTime(Date source) {
        Calendar install = Calendar.getInstance();
        install.setTime(source);
        install.set(Calendar.MILLISECOND, 0);
        return install.getTime();
    }


    public static String format(Date source, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(source);
    }

    public static String format(Date source) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME);
        return sdf.format(source);
    }


    /**
     * @param date   原时间
     * @param field  单位 calender.date, calender.month ....
     * @param amount 数量
     * @return
     */
    public static Date add(Date date, int field, int amount) {//
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(field, amount);
        return c.getTime();
    }

    /**
     * 获取当前时间作为序列号
     *
     * @return
     */
    public static String getSeqnum() {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_SEQNUM);
        return sdf.format(new Date());
    }

    /**
     * 分钟转天和小时
     *
     * @param i
     * @return
     */
    public static String getSubTimeStr(Integer i) {

        if (i == -999) {
            return "";
        }

        int fz = i;
        int hour = 0;
        int min = 0;
        if (fz < 60) {
            return fz  + "分钟";
        } else if (fz < 1440) {
            hour = fz / 60;//小时
            min = fz % 60;//分钟
            double add = DecimalUtil.add((double) hour, (double) min / 60);
            String result = String.format("%.2f", add);
            return result + "小时";
        }
        int day = fz / 1440;
        hour = (fz - day * 1440) / 60;
        min = fz - (hour * 60 + day * 1440);
        double add = DecimalUtil.add((double) hour, (double) min / 60);
        String result = String.format("%.2f", add);
        return day + "天" + result + "小时";
    }



    /**
     * 时间做减法，得到时长(毫秒)
     */
    public static long getSubTimeLong(String beginTime, String endTime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date time1 = sdf.parse(beginTime);
            Date time2 = sdf.parse(endTime);
            long time = time2.getTime() - time1.getTime();
            return time;
        } catch (ParseException e) {
            logger.error(ExceptionUtil.getStackTrace(e));
        }
        return 0;
    }

    /**
     * 时间做减法，得到时长
     */
    public static String getSubTimeStr(String beginTime, String endTime) {
        // 毫秒数
        long time = getSubTimeLong(beginTime, endTime);

        if (0 == time) {
            return null;
        }

        // 总共多少分钟
        int fz = (int) (time / (60 * 1000));

        if (fz < 60) {
            return fz + "分钟";
        }

        int hour = fz / 60;// 多少小时
        int min = fz % 60;// 多少分钟
        return hour + "小时" + min + "分钟";
    }

    public static Integer getSubTimeInt(String beginTime, String endTime) {
        // 毫秒数
        long time = getSubTimeLong(beginTime, endTime);

        if (0 == time) {
            return null;
        }

        // 总共多少分钟
        int fz = (int) (time / (60 * 1000));

        return fz;
    }

    public static String curMonthStr() {
        return DateUtil.format(new Date(), "yyyy-MM");
    }

    public static String nextMonthStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, 1);
        return DateUtil.format(calendar.getTime(), "yyyy-MM");
    }

    /**
     * 返回指定模板的数据
     *
     * @param date
     * @param template
     * @return
     * @throws ParseException
     */
    public static String changeDateFormat(String date, String template) throws ParseException {
        if (date == null || "".equals(date)) {
            return "";
        }
        Date sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(template);
        return simpleDateFormat.format(sdf);
    }

    /**
     * 字符串转换为日期
     *
     * @param formatStr 要转换的字符串
     * @param format    自格式化样式（如：yyyy-MM-dd HH:mm:ss）
     * @return
     */
    public static Date strToDate(String formatStr, String format) {
        if (format == null || format.isEmpty()) {
            format = FORMAT_DATETIME;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(formatStr);
        } catch (ParseException e) {
            logger.error("时间转换错误", e);
            return null;
        }
    }

    /**
     * 日期转换为字符串
     *
     * @param date   要转换的日期
     * @param format 自格式化样式（如：yyyy-MM-dd HH:mm:ss）
     * @return
     */
    public static String dateToStr(Date date, String format) {
        if (format == null || format.isEmpty()) {
            format = FORMAT_DATETIME;
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            return simpleDateFormat.format(date);
        } catch (Exception e) {
            logger.error("时间转换错误", e);
            return "";
        }
    }

    /**
     * 日期增加
     *
     * @param source 原时间(String 格式)
     * @param field  单位 calender.date, calender.month ....
     * @param amount 数量
     * @return
     */
    public static String add(String source, int field, int amount) {
        Date dateSource = strToDate(source, null);
        Date date = add(dateSource, field, amount);
        return dateToStr(date, null);
    }

    /**
     * 今天加N天时间
     *
     * @param n
     * @return
     */
    public static Date getNextDate(Integer n) {
        return add(new Date(), Calendar.DAY_OF_MONTH, n);
    }

    /**
     * 指定时间加N天时间
     *
     * @param source String格式日期
     * @param n
     * @return String格式日期
     */
    public static String getNextDate(String source, Integer n) {
        if (StringUtils.isEmpty(source)) {
            return "";
        }
        Date dateSource = strToDate(source, null);
        Date date = add(dateSource, Calendar.DAY_OF_MONTH, n);
        return dateToStr(date, null);
    }

    /**
     * 比较两个日期大小
     *
     * @param date1 Date格式
     * @param date2 Date格式
     * @return 结果等于0，两者相同；结果大于0，date1大于date2;结果小于0，date1小于date2
     */
    public static Integer compareDate(Date date1, Date date2) {
        return date1.compareTo(date2);
    }

    /**
     * 比较两个日期大小
     *
     * @param date1 String格式
     * @param date2 String格式
     * @return 结果等于0，两者相同；结果大于0，date1大于date2;结果小于0，date1小于date2
     */
    public static Integer compareDate(String date1, String date2) {
        Date date = strToDate(date1, null);
        Date anotherDate = strToDate(date2, null);
        return date.compareTo(anotherDate);
    }

    /**
     * @param beginTime 开始时间
     * @param template  指定毫秒数
     * @return
     * @throws ParseException
     */
    public static String getLongLaterTime(String beginTime, long template) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begin = sdf.parse(beginTime);
        long l = begin.getTime() + template;
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(l));
        return date;
    }


    public static String getTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }
    /**
     * @Author xiaowei
     * @CreateTime 2019/9/27 10:20
     * @MethodDesc 传入两个字符串或者date类型的时间，返回一个相差的天数、时分秒，判断了是否大于0天
     * @param oneTime
     * @param twoTime
     * @return {@link Map<String,Object>}
     */
    public static String getTime(Object oneTime, Object twoTime) {
        String differTime = "";
        Date startDate;
        Date endDate;
        if(oneTime instanceof String && twoTime instanceof String){
            // String-date，默认是"yyyy-MM-dd HH:mm:ss"
            startDate = strToDate((String) oneTime, null);
            endDate = strToDate((String) twoTime, null);
        }else if(oneTime instanceof Date && twoTime instanceof Date){
            startDate = (Date) oneTime;
            endDate = (Date) twoTime;

        }else {
            return "请输入正确的时间格式！";
        }
        // 定义计算时间的参数
        long differDay = 1000 * 24 * 60 * 60;// 相差天
        long differHour = 1000 * 60 * 60;// 相差小时
        long differMinute = 1000 * 60;// 相差分钟
        long differSecond = 1000;// 相差秒

        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();

        // 计算差多少天
        long day = diff / differDay;
        if(day >= 1){
            differTime = differTime + day + "天";
        }
        // 计算差多少小时
        long hour = diff % differDay / differHour;
        differTime = differTime + hour + "小时";
        // 计算差多少分钟
        long min = diff % differDay % differHour / differMinute;
        differTime = differTime + min + "分钟";
        // 计算差多少秒
        long sec = diff % differDay % differHour % differMinute / differSecond;
        differTime = differTime + sec + "秒";
        return differTime;
    }

    //两个时间相减
    /*
    public static String getTime(String time1, String time2) {
        String time = "";
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = df.parse(time2);
            Date d2 = df.parse(time1);
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是毫秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            if(days > 0) {
                time = days + "天" + hours + "小时" + minutes + "分钟";
            } else if(days ==0){
                time = hours + "小时" + minutes + "分钟";
            }
            System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }
    */

    /**
     * 指定日期加上天数后的日期
     *
     * @param startDay 指定日期
     * @param count    天数
     * @return
     */
    public static String getAfterDay(String startDay, int count) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(startDay);
            Calendar cl = Calendar.getInstance();
            cl.setTime(date);
            cl.add(Calendar.DATE, count);
            return sdf.format(cl.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 计算日期
     * @param startDay 计算的时间
     * @param count 减去的天数
     * @return
     * @throws Exception
     */
    public static String getBeforeDay(String startDay, int count) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(startDay);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, -count);
            //cal.add(Calendar.MONTH, -day); 月数
            //cal.add(Calendar.YEAR, -day); //年份
            return sdf.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
	 * 当前时间（yyyy-MM-dd HH:mm:ss）
	 * @return
	 */
	public static String now() {
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT_DATETIME);
			return simpleDateFormat.format(new Date());
		} catch (Exception e) {
			logger.error("时间转换错误", e);
			return "";
		}
	}

    /**
     * @Author xiaowei
     * @CreateTime 2020/1/8 10:43
     * @MethodDesc 将日期推后
     * @param dateStr 要推迟的日期
     * @param yearAdd 推迟年数
     * @param monthAdd 推迟月数
     * @param dayAdd 推迟天数
     * @param hourAdd 推迟的小时
     * @param formatStr 日期格式
     * @return {@link String}
     */
    public static String getAddMonth(String dateStr, int yearAdd, int monthAdd, int dayAdd, int hourAdd, String formatStr) {
        if (dateStr == null || dateStr.equals("")) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        Calendar cal = Calendar.getInstance();
        Date newDate = null;
        try {
            Date date = sdf.parse(dateStr);
            cal.setTime(date);
            int year = cal.get(Calendar.YEAR) + yearAdd;
            int month = cal.get(Calendar.MONTH) + 1 + monthAdd;
            int day = cal.get(Calendar.DATE) + dayAdd;

            int hour = cal.get(Calendar.HOUR_OF_DAY) + hourAdd;
            int minute = cal.get(Calendar.MINUTE);

            newDate = sdf.parse(year + "-" + month + "-" + day + " " + hour + ":" + minute);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DateUtil.defaultFormat(newDate, formatStr);
    }
    /**
     * 缺省格式化日期，返回指定格式日期
     * @param date
     * @return
     */
    public static String defaultFormat(Date date, String format) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sf = new SimpleDateFormat(format);
        return sf.format(date);
    }

    /**
     * 获得某月最后一天
     *
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    }

    /**
     * @Author xiaowei
     * @CreateTime 2020/1/8 11:21
     * @MethodDesc 请在此填写当前方法的描述
     * @param date1 String格式
     * @param date2 String格式
     * @param FORMAT_DATE 时间格式
     * @return {@link Integer}
     */
    public static Integer compareDate(String date1, String date2, String FORMAT_DATE) {
        Date date = strToDate(date1, FORMAT_DATE);
        Date anotherDate = strToDate(date2, FORMAT_DATE);
        return date.compareTo(anotherDate);
    }
	
    public static void main(String[] args) {
        String weekOfDate = getWeekOfDate(new Date());
        //System.err.println(weekOfDate);
        String getTime = getTime("2004-03-26 13:31:40", "2004-03-26 13:32:40");
        String str2 = getAfterDay("2004-03-26 13:32:40", 2);
        String str3 = getBeforeDay("2004-03-26 13:32:40", 2);


        int flag = compareDate("2004-03-28 13:31:40", "2004-03-27 13:32:40");
        System.out.println(getTime +"AA:"+str2+"==="+flag+"str3=="+str3);


        String time = getTime("2004-03-26 13:31:40", "2004-03-27 13:32:41");
        System.out.println(time);
    }

}

